/* api */
import { addQuestionToStandardLib, deleteBaoGPTQuestion, generateSimilarQuestions, getBaoGPTQuestion, getBaoGPTQuestionCount, getBaoGPTQuestionList, getBaoGPTQuestionLogList, insertStandardQuestion, updateStandardQuestion } from '@src/api/AIApi';
/* hooks */
import { useLoading } from '@hooks/useLoading'
import { useSettingListSearch } from '@src/modules/setting/gpt/hooks/search';
/* model */
import MsgModel from '@model/MsgModel'
import {
  SettingGPTQuestionTypeEnum, SettingGPTQuestionTypeValueEnum
} from '@src/modules/setting/gpt/model';
import { 
  AddQuestionToStandardLibModel, 
  DeleteBaoGPTQuestionModel, 
  GenerateSimilarQuestionsModel, 
  GetBaoGPTLogListModel, 
  GetBaoGPTQuestionListModel, 
  GetBaoGPTQuestionModel, 
  InsertStandardQuestionModel, 
  UpdateStandardQuestionModel 
} from '@model/param/in/AI';
import Page from '@model/Page.ts';
/* util */
import { message } from '@src/util/message'
import platform from '@src/util/platform';
/* vue */
import { computed, Ref, ref } from 'vue'
import { EmitFn } from 'vue/types/v3-setup-context';
/* types */
import { 
  SettingGPTLogItemType,
  SettingGPTQuestionCountType,
  SettingGPTQuestionItemType
} from '@src/modules/setting/gpt/types';
import { isEmpty, isFalsy } from '@src/util/type';
import { debounce } from 'pub-bbx-utils';
import { formatSimilarQuestions } from '@gpt/utils';

/** 
 * @description 小宝 GPT 问题列表
*/
function useSettingGPTQuestionList() {
  
  // 搜索参数
  const { searchParams, setPageNum, setPageSize, resetPage, setKeyword } = useSettingListSearch()
  // 选项卡
  const { setActive, active, isDisLikeActive, isLikeActive, isUnknownActive, isLogActive, isAllActive, isStandardActive } = useSettingGPTQuestionTab()
  // 问题数量
  const { 
    loading: fetchQuestionCountLoading,
    countMap, 
    fetchQuestionCount 
  } = useFetchSettingGPTQuestionCount()
  // 删除
  const {
    loading: fetchQuestionDeleteLoading,
    isSuccess: fetchQuestionDeleteIsSuccess,
    fetchQuestionDelete
  } = useFetchSettingGPTQuestionDelete()
  
  // 获取 问题列表
  const { 
    loading: fetchQuestionListLoading,
    questionPage,
    questionList,
    fetchQuestionList
  } = useFetchSettingGPTQuestionList()
  
  // 日志列表
  const {
    loading: fetchQuestionLogListLoading,
    logPage,
    logList,
    fetchQuestionList: fetchQuestionLogList
  } = useFetchSettingGPTLogList()
  
  // 加载状态
  const loading = computed(() => {
    return (
      fetchQuestionListLoading.value
      || fetchQuestionDeleteLoading.value
      || fetchQuestionLogListLoading.value
      || fetchQuestionCountLoading.value
    )
  })
  
  const fetchList = () => {
    
    // 日志
    if (isLogActive.value) {
      return fetchQuestionLogList({
        ...searchParams.value
      })
    }
    
    // 问题
    let params: GetBaoGPTQuestionListModel = {
      ...searchParams.value,
    }
    
    // 全部
    if (isAllActive.value) {
      params.typeList = [
        SettingGPTQuestionTypeValueEnum[SettingGPTQuestionTypeEnum.Like],
        SettingGPTQuestionTypeValueEnum[SettingGPTQuestionTypeEnum.Dislike],
        SettingGPTQuestionTypeValueEnum[SettingGPTQuestionTypeEnum.Unknown],
      ]
    } else {
      // @ts-ignore
      params.type = SettingGPTQuestionTypeValueEnum[active.value]
    }
    
    return fetchQuestionList(params)
    
  }
  
  const keyword = computed(() => searchParams.value.keyword)
  
  const dataList = computed(() => {
    return isLogActive.value ? logList.value : questionList.value
  })
  
  const page = computed(() => {
    return isLogActive.value ? logPage.value : questionPage.value
  })
  
  const debounceFetchList = debounce(fetchList, 300)
  const debounceFetchQuestionCount = debounce(fetchQuestionCount, 300)
  
  // 初始化
  const initialize = () => {
    fetchQuestionCount()
    fetchList()
  }
  
  const onSetPageNumHandler = (pageNum: number) => {
    setPageNum(pageNum)
    fetchList()
  }
  
  const onSetPageSizeHandler = (pageSize: number) => {
    setPageSize(pageSize)
    fetchList()
  }
  
  const onTabChangeHandler = (tabValue: SettingGPTQuestionTypeEnum) => {
    setActive(tabValue)
    resetPage()
    fetchList()
  }
  
  const onRefreshHandler = () => {
    resetPage()
    fetchList()
    debounceFetchQuestionCount()
  }
  
  const onKeywordChangeHandler = (keyword: string) => {
    setKeyword(keyword)
    debounceFetchList()
  }
  
  const onDeleteQuestionHandler = async (row: SettingGPTQuestionItemType) => {
    
    const confirmed = await platform.confirm('确定删除该问题吗？')
    
    if (isFalsy(confirmed)) {
      return
    }
    
    const id = row.id || ''
    
    const params: DeleteBaoGPTQuestionModel = {
      ids: [id]
    }
    
    fetchQuestionDelete(params).then(() => {
      if (fetchQuestionDeleteIsSuccess.value) {
        fetchList()
        debounceFetchQuestionCount()
      }
    })
    
  }
  
  const onDeleteBatchQuestionHandler = async (rows: SettingGPTQuestionItemType[]) => {
    
    const ids = rows.map(row => row.id || '')
    
    if (isEmpty(ids)) {
      platform.alert('请选择需要删除的问题')
      return
    }
    
    const confirmed = await platform.confirm('确定删除选择的问题吗？')
    
    if (isFalsy(confirmed)) {
      return
    }
    
    const params: DeleteBaoGPTQuestionModel = {
      ids
    }
    
    return (
      fetchQuestionDelete(params).then(async () => {
        if (fetchQuestionDeleteIsSuccess.value) {
          await fetchList()
          resetPage()
          debounceFetchQuestionCount()
        }
      })
    )
    
  }
  
  return {
    loading,
    dataList,
    page,
    active,
    status,
    isLogActive,
    isDisLikeActive,
    isLikeActive,
    isUnknownActive,
    keyword,
    isStandardActive,
    countMap,
    onRefreshHandler,
    resetPage,
    setActive,
    onKeywordChangeHandler,
    onTabChangeHandler,
    initialize,
    onSetPageNumHandler,
    onSetPageSizeHandler,
    onDeleteQuestionHandler,
    onDeleteBatchQuestionHandler
  }
}

/** 
 * @description 问题类型 选项卡
*/
function useSettingGPTQuestionTab() {
  
  const active: Ref<SettingGPTQuestionTypeEnum> = ref(SettingGPTQuestionTypeEnum.All)
  
  const setActive = (type: SettingGPTQuestionTypeEnum) => {
    active.value = type
  }
  
  const isActive = (type: SettingGPTQuestionTypeEnum) => {
    return active.value === type
  }
  
  const isLikeActive = computed(() => {
    return isActive(SettingGPTQuestionTypeEnum.Like)
  })
  
  const isDisLikeActive = computed(() => {
    return isActive(SettingGPTQuestionTypeEnum.Dislike)
  })
  
  const isUnknownActive = computed(() => {
    return isActive(SettingGPTQuestionTypeEnum.Unknown)
  })
  
  const isLogActive = computed(() => {
    return isActive(SettingGPTQuestionTypeEnum.Log)
  })
  
  const isAllActive = computed(() => {
    return isActive(SettingGPTQuestionTypeEnum.All)
  })
  
  const isStandardActive = computed(() => {
    return isActive(SettingGPTQuestionTypeEnum.Standard)
  })
  
  const resetActive = () => {
    setActive(SettingGPTQuestionTypeEnum.All)
  }
  
  return {
    active,
    setActive,
    resetActive,
    isLogActive,
    isAllActive,
    isLikeActive,
    isDisLikeActive,
    isUnknownActive,
    isStandardActive
  }
}

/** 
 * @description 问题列表 下拉
*/
function useSettingGPTQuestionSelect() {
  
  const chatType: Ref<string> = ref('')
  const status: Ref<string> = ref('')
  
  const setChatType = (type: string) => {
    chatType.value = type
  }
  
  const setStatus = (type: string) => {
    status.value = type
  }
  
  const resetChatType = () => {
    setChatType('')
  }
  
  const resetStatus = () => {
    setStatus('')
  }
  
  const reset = () => {
    resetChatType()
    resetStatus()
  }
  
  return {
    chatType,
    status,
    setChatType,
    setStatus,
    resetChatType,
    resetStatus,
    reset
  }
}

/**
 * @description 获取 小宝 GPT 问题列表
 */
function useFetchSettingGPTQuestionList() {
  
  const { loading, setLoading, clearLoading } = useLoading()
  
  const questionList: Ref<SettingGPTQuestionItemType[]> = ref([])
  const questionPage: Ref<Page<SettingGPTQuestionItemType[]>> = ref(new Page())
  
  const fetchQuestionList = (params: GetBaoGPTQuestionListModel) => {
    
    setLoading()
    
    return (
      getBaoGPTQuestionList(params).then(result => {
        
        if (MsgModel.isSuccess(result)) {
          
          const page = result.data || new Page()
          const data = page?.content || page?.list || []
          
          questionList.value = data
          questionPage.value = page
          
        } else {
          message.error(result.message)
        }
        
      }).finally(() => {
        clearLoading()
      })
    )
  }
  
  return {
    loading,
    questionList,
    questionPage,
    fetchQuestionList
  }
}

/**
 * @description 获取 小宝 GPT 问题
 */
function useFetchSettingGPTQuestion() {
  
  const { loading, setLoading, clearLoading } = useLoading()
  
  const question: Ref<SettingGPTQuestionItemType> = ref({} as any)
  
  const fetchQuestion = (params: GetBaoGPTQuestionModel) => {
    
    setLoading()
    
    return (
      getBaoGPTQuestion(params).then(result => {
        
        const isSuccess = MsgModel.isSuccess(result)
        
        if (isSuccess) {
          
          question.value = MsgModel.getData(result, {} as SettingGPTQuestionItemType)
          
        } else {
          message.error(result.message)
        }
        
        return isSuccess
        
      }).finally(() => {
        clearLoading()
      })
    )
  }
  
  return {
    loading,
    question,
    fetchQuestion
  }
}

/**
 * @description 获取 小宝 GPT 问题 数量
 */
function useFetchSettingGPTQuestionCount() {
  
  const { loading, setLoading, clearLoading } = useLoading()
  
  const countMap: Ref<SettingGPTQuestionCountType> = ref<SettingGPTQuestionCountType>({
    likeCount: 0,
    dislikeCount: 0,
    unknownCount: 0
  })
  
  const fetchQuestionCount = () => {
    
    setLoading()
    
    return (
      getBaoGPTQuestionCount().then(result => {
        
        if (MsgModel.isSuccess(result)) {
          
          countMap.value = MsgModel.getData(result, {
            likeCount: 0,
            dislikeCount: 0,
            unknownCount: 0
          })
          
        } else {
          message.error(result.message)
        }
        
      }).finally(() => {
        clearLoading()
      })
    )
  }
  
  return {
    loading,
    countMap,
    fetchQuestionCount
  }
}

/**
 * @description 获取 小宝 GPT 日志列表
 */
function useFetchSettingGPTLogList() {
  
  const { loading, setLoading, clearLoading } = useLoading()
  
  const logList: Ref<SettingGPTLogItemType[]> = ref([])
  const logPage: Ref<Page<SettingGPTLogItemType[]>> = ref(new Page())
  
  const fetchQuestionList = (params: GetBaoGPTLogListModel) => {
    
    setLoading()
    
    return (
      getBaoGPTQuestionLogList(params).then(result => {
        
        if (MsgModel.isSuccess(result)) {
          
          const page = result.data || new Page()
          const data = page?.content || page?.list || []
          
          logList.value = data
          logPage.value = page
          
        } else {
          message.error(result.message)
        }
        
      }).finally(() => {
        clearLoading()
      })
    )
  }
  
  return {
    loading,
    logPage,
    logList,
    fetchQuestionList
  }
}

/**
 * @description 删除 小宝 GPT 问题
 */
function useFetchSettingGPTQuestionDelete() {
  
  const { loading, setLoading, clearLoading } = useLoading()
  
  const isSuccess = ref(false)
  
  const fetchQuestionDelete = (params: DeleteBaoGPTQuestionModel) => {
    
    setLoading()
    
    return (
      deleteBaoGPTQuestion(params).then(result => {
        
        isSuccess.value = MsgModel.isSuccess(result)
        
        if (isSuccess.value) {
          
        } else {
          message.error(result.message)
        }
        
        return isSuccess.value
        
      }).finally(() => {
        clearLoading()
      })
    )
  }
  
  return {
    loading,
    isSuccess,
    fetchQuestionDelete
  }
}

/**
 * @description 生成相似问题
 */
function useFetchSettingGPTGenerateSimilarQuestions() {
  
  const { loading, setLoading, clearLoading } = useLoading()
  
  const isSuccess = ref(false)
  const similarQuestions: Ref<string[]> = ref([])
  
  const fetchGenerateSimilarQuestions = (params: GenerateSimilarQuestionsModel) => {
    
    setLoading()
    
    similarQuestions.value = []
    
    return (
      generateSimilarQuestions(params).then(result => {
        
        isSuccess.value = MsgModel.isSuccess(result)
        
        if (isSuccess.value) {
          const data: string[] = MsgModel.getData(result, [])
          similarQuestions.value = formatSimilarQuestions(data)
        } else {
          message.error(result.message)
        }
        
      }).finally(() => {
        clearLoading()
      })
    )
  }
  
  return {
    loading,
    isSuccess,
    fetchGenerateSimilarQuestions,
    similarQuestions
  }
}

/**
 * @description 添加问题到标准库/应用百科
 */
function useFetchSettingGPTAddQuestionToStandardLib() {
  
  const { loading, setLoading, clearLoading } = useLoading()
  
  const isSuccess = ref(false)
  
  const fetchAddQuestionToStandardLib = (params: AddQuestionToStandardLibModel) => {
    
    setLoading()
    
    return (
      addQuestionToStandardLib(params).then(result => {
        
        isSuccess.value = MsgModel.isSuccess(result)
        
        if (isSuccess.value) {
          
        } else {
          message.error(result.message)
        }
        
        return isSuccess.value
        
      }).finally(() => {
        clearLoading()
      })
    )
  }
  
  return {
    loading,
    isSuccess,
    fetchAddQuestionToStandardLib
  }
}

/**
 * @description 新增标准问题
 */
function useFetchSettingGPTInsertStandardQuestion() {
  
  const { loading, setLoading, clearLoading } = useLoading()
  
  const isSuccess = ref(false)
  
  const fetchInsertStandardQuestion = (params: InsertStandardQuestionModel) => {
    
    setLoading()
    
    return (
      insertStandardQuestion(params).then(result => {
        
        isSuccess.value = MsgModel.isSuccess(result)
        
        if (isSuccess.value) {
          
        } else {
          message.error(result.message)
        }
        
      }).finally(() => {
        clearLoading()
      })
    )
  }
  
  return {
    loading,
    isSuccess,
    fetchInsertStandardQuestion
  }
}

/**
 * @description 更新标准问题
 */
function useFetchSettingGPTUpdateStandardQuestion() {
  
  const { loading, setLoading, clearLoading } = useLoading()
  
  const isSuccess = ref(false)
  
  const fetchUpdateStandardQuestion = (params: UpdateStandardQuestionModel) => {
    
    setLoading()
    
    return (
      updateStandardQuestion(params).then(result => {
        
        isSuccess.value = MsgModel.isSuccess(result)
        
        if (isSuccess.value) {
          
        } else {
          message.error(result.message)
        }
        
      }).finally(() => {
        clearLoading()
      })
    )
  }
  
  return {
    loading,
    isSuccess,
    fetchUpdateStandardQuestion
  }
}

export {
  useSettingGPTQuestionList,
  useSettingGPTQuestionTab,
  useFetchSettingGPTQuestionList,
  useFetchSettingGPTLogList,
  useFetchSettingGPTQuestionDelete,
  useFetchSettingGPTGenerateSimilarQuestions,
  useFetchSettingGPTAddQuestionToStandardLib,
  useFetchSettingGPTInsertStandardQuestion,
  useFetchSettingGPTUpdateStandardQuestion,
  useFetchSettingGPTQuestion,
}